package com.android.djlmapp.activity.kuandai;

import android.content.Intent;
import android.os.Bundle;
import android.support.constraint.ConstraintLayout;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.RadioButton;
import android.widget.TextView;
import android.widget.Toast;

import com.android.djlmapp.R;
import com.android.djlmapp.adapter.kaika.SelectNumAdapter;
import com.android.djlmapp.adapter.kaika.SelectNumPopAdapter;
import com.android.djlmapp.application.MyApplication;
import com.android.djlmapp.base.BaseActivity;
import com.android.djlmapp.http.GlobalUrls;
import com.android.djlmapp.model.kaika.SelectNumInfo;
import com.android.djlmapp.popupwindow.CommonPopupWindow;
import com.android.djlmapp.popupwindow.CommonPopupWindow.LayoutGravity;
import com.android.djlmapp.tools.global.GlobalUtils;
import com.android.djlmapp.tools.global.KeyBordUtils;
import com.android.djlmapp.tools.global.ToastUtils;
import com.android.djlmapp.view.DropdownButton;
import com.google.gson.Gson;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.Response;

import org.refresh_view.pullrecyclerview.PullRecyclerView;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

import static com.android.djlmapp.activity.kaika.SelectNumActivity.PAGE_DATA_URL_KEY;

public class SelectKuanDaiNumActivity extends BaseActivity {

    @BindView(R.id.ll_top_back)
    LinearLayout llTopBack;
    @BindView(R.id.tv_name)
    TextView tvName;
    @BindView(R.id.iv_top_msg)
    ConstraintLayout ivTopMsg;
    @BindView(R.id.iv_top_set)
    ImageView ivTopSet;
    @BindView(R.id.iv_top_kf)
    ImageView ivTopKf;
    @BindView(R.id.db_hmlx)
    DropdownButton dbHmlx;
    @BindView(R.id.db_hmd)
    DropdownButton dbHmd;
    @BindView(R.id.db_lhlx)
    DropdownButton dblhLx;
    @BindView(R.id.db_lhf)
    DropdownButton dblhF;
    @BindView(R.id.ed_search)
    EditText edSearch;
    @BindView(R.id.ll_type)
    LinearLayout llType;
    @BindView(R.id.pull_recycler_view)
    PullRecyclerView pullRecyclerView;
    private ArrayList<String> list = new ArrayList<>();

    // 号码类型
    private String[] ltHmlxs = new String[]{"不限", "联通4G", "网卡", "固话", "专用号码", "带4", "不带4"};
    private String[] hmlxs = new String[]{"", "1", "4", "9", "313", "in_4", "no_4"};

    // 号码段
    private String[] ltHmds = new String[]{"不限", "130", "131", "132", "145", "155", "156", "166",
            "175", "176", "185", "186"};
    private String[] hmds = new String[]{"", "130", "131", "132", "145", "155", "156", "166", "175", "176", "185", "186"};

    // 靓号类型
    private String[] ltlhLxs = new String[]{"不限", "中间AA", "中间AAA", "中间AABB", "中间AABBB",
            "尾数AA", "尾数AAA", "尾数AAAB", "尾数AABB", "尾数ABAB", "尾数ABBA", "尾数ABC"};

    private String[] lhLxs = new String[]{"", "c_AA", "c_AAA", "c_AABB", "c_AABBB", "e_AA", "e_AAA", "e_AAAB", "e_AABB", "e_ABAB", "e_ABBA", "e_ABC"};

    // 靓号费
    private String[] ltlhFs = new String[]{"不限", "0", "1-100", "101-300", "301-500", "501-1200",
            "1201-1500", "1501-3000", "3000以上"};
    private String[] lhFs = new String[]{"", "0", "1", "2", "3", "4", "5", "6", "7"};


    private CommonPopupWindow window;
    private ListView popList;
    private SelectNumPopAdapter popAdapter;
    private LayoutGravity layoutGravity;
    private PopupWindow popupWindow;
    private DropdownButton curentBtn;

    private List<SelectNumInfo.PhoneList> listNumData = new ArrayList<>();
    private String simNum;
    private String jiTuanNum;
    private String heYueId;
    private String addPara;

    String haomaType = ""; // 号码类型
    String haomaDuan = ""; // 号码段
    String lhLx = ""; // 靓号类型
    String lhF = ""; // 靓号费

    private int page = 1; // 加载页数
    private SelectNumAdapter selectNumAdapter;

    private int selectPosition1 = 0; // 选中的条目位置
    private int selectPosition2 = 0;// 选中的条目位置
    private int selectPosition3 = 0;// 选中的条目位置
    private int selectPosition4 = 0;// 选中的条目位置
    private String yeWuType;

    public Map<String, String> mOtherParams = new HashMap<>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_select_num);
        ButterKnife.bind(this);
        initView();
        // 创建弹窗
        createPopupWindow();
        initData();
    }

    @Override
    protected void initView() {
        mOtherParams.put(PAGE_DATA_URL_KEY, GlobalUrls.SEARCH_NUM);
        llTopBack.setVisibility(View.VISIBLE);
        ivTopMsg.setVisibility(View.GONE);
        ivTopSet.setVisibility(View.GONE);
        ivTopKf.setVisibility(View.VISIBLE);
        tvName.setText("选择号码");

        // 业务类型
        yeWuType = getIntent().getStringExtra("KDTYPE");
        Log.e("项目异常", "------yeWuType111------" + yeWuType);
        // 监听软键盘回车事件
        edSearch.setOnEditorActionListener(new TextView.OnEditorActionListener() {

            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_SEND
                        || actionId == EditorInfo.IME_ACTION_DONE
                        || actionId == EditorInfo.IME_ACTION_NONE
                        || actionId == EditorInfo.IME_ACTION_GO
                        || actionId == EditorInfo.IME_ACTION_SEARCH
                        || actionId == EditorInfo.IME_ACTION_NEXT
                        || (event != null && KeyEvent.KEYCODE_ENTER
                        == event.getKeyCode() && KeyEvent.ACTION_DOWN
                        == event.getAction())) {
                    if (popupWindow != null) {
                        popupWindow.dismiss();
                    }
                    pullRecyclerView.autoRefresh();
                }
                return false;
            }
        });

        getKaiKaData();
        initTab();
        initRecycleView();

    }

    /**
     * 初始化数据显示列表
     */
    private void initRecycleView() {

        selectNumAdapter = new SelectNumAdapter(SelectKuanDaiNumActivity.this);
        selectNumAdapter.addAll(listNumData);
        // 设置可以加载
        pullRecyclerView.enableLoadMore(true);
        // 设置Adapter
        pullRecyclerView.setAdapter(selectNumAdapter);

        selectNumAdapter.setOnItemClickListener(item -> {

            String phonenum = item.getPhonenum();
            // 保存数据,返回界面
            Intent intent = new Intent();
            intent.putExtra("PHONE_NUM", phonenum); // 获取SIM卡号
            setResult(RESULT_OK, intent);
            finish();


        });
        pullRecyclerView.setColorSchemeResources(R.color.colorAccent);
        pullRecyclerView.setOnRecyclerRefreshListener(new PullRecyclerView.OnRecyclerRefreshListener() {
            @Override
            public void onPullRefresh() {
                if (curentBtn != null && curentBtn.getChecked()) {
                    curentBtn.setChecked(false);
                }
                if (popupWindow != null && popupWindow.isShowing()) {
                    popupWindow.dismiss();
                }
                // 刷新
                pullRecyclerView.enableLoadDoneTip(false, R.string.load_done_tip);
                page = 1;

                selectNumAdapter.clear();
                getNumData();
            }

            @Override
            public void onLoadMore() {
                // 加载
                pullRecyclerView.enableLoadDoneTip(true, R.string.load_done_tip);
                getNumData();
            }
        });
    }

    /**
     * 初始化类型标签
     */
    private void initTab() {
        dbHmlx.setText("号码类型");
        dbHmd.setText("号码段");
        dblhLx.setText("靓号类型");
        dblhF.setText("靓号费");

        dbHmlx.setChecked(false);
        dbHmd.setChecked(false);
        dblhLx.setChecked(false);
        dblhF.setChecked(false);
    }

    /**
     * 获取开卡传递数据
     */
    private void getKaiKaData() {
        simNum = getIntent().getStringExtra("ICCIDNO");
        jiTuanNum = getIntent().getStringExtra("JTBM");
        heYueId = getIntent().getStringExtra("HEYUEID");
        addPara = getIntent().getStringExtra("ADDPARA");
        Log.e("项目异常getNumData", heYueId + "------getKaiKaData------" + addPara + "------1------" + simNum);
        if (TextUtils.isEmpty(simNum)) {
            simNum = "";
        }
        if (TextUtils.isEmpty(jiTuanNum)) {
            jiTuanNum = "";
        }
        if (TextUtils.isEmpty(heYueId)) {
            heYueId = "";
        }
        if (TextUtils.isEmpty(addPara)) {
            addPara = "";
        }
        Log.e("项目异常getNumData", heYueId + "------getKaiKaData------" + addPara + "------1------" + simNum);
    }

    @Override
    protected void initData() {
        pullRecyclerView.autoRefresh();
    }

    private void getNumData() {
        String searchStr = edSearch.getText().toString().trim();
        Log.e("项目异常getNumData", haomaType + "--" + haomaDuan + "--" + lhLx + "--" + lhF + "--" + searchStr);
        MyApplication.getInstance().getHttpTools().getSelectNumData(yeWuType,"", addPara, simNum, heYueId, jiTuanNum,
                searchStr, haomaType, haomaDuan, lhF, lhLx, new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        try {
                            searchParseJson(response.body());
                        } catch (Exception e) {
                            e.printStackTrace();
                            ToastUtils.showShortToast(SelectKuanDaiNumActivity.this, "数据解析异常");
                        }
                    }

                    @Override
                    public void onError(Response<String> response) {
                        super.onError(response);
                        page = 1;
                        Log.e("项目异常onError", "------1------" + response.body());
                        ToastUtils.showShortToast(SelectKuanDaiNumActivity.this, "网络或服务器错误");
                    }

                    @Override
                    public void onFinish() {
                        super.onFinish();
                        if (pullRecyclerView != null) {
                            pullRecyclerView.postDelayed(() -> {
                                pullRecyclerView.stopLoadMore();
                                pullRecyclerView.stopRefresh();
                            }, 300);
                        }
                    }
                }, mOtherParams);
    }

    private void searchParseJson(String json) {
        Log.e("项目异常getNumData", "------searchParseJson------" + json);
        Gson gson = new Gson();
        SelectNumInfo info = gson.fromJson(json, SelectNumInfo.class);
        if (info != null) {
            if (info.getCode() < 1000) {
                ArrayList<SelectNumInfo.PhoneList> phone_list = info.getPhone_list();
                if (phone_list != null && phone_list.size() > 0) {
                    //                    page++; // 要是分页加载就放开
                    selectNumAdapter.addAll(phone_list);
                } else {
                    page = 1;
                    Toast.makeText(SelectKuanDaiNumActivity.this,
                            "没有更多数据了", Toast.LENGTH_SHORT).show();
                }
            } else {
                page = 1;
                ToastUtils.showShortToast(SelectKuanDaiNumActivity.this, info.getMsg());
            }
        } else {
            page = 1;
            ToastUtils.showShortToast(SelectKuanDaiNumActivity.this, "未获取到数据");
        }
    }

    @OnClick({R.id.db_hmlx, R.id.db_hmd, R.id.db_lhlx, R.id.db_lhf})
    public void onViewClicked(View view) {

        switch (view.getId()) {
            case R.id.db_hmlx:
                popAdapter.clear();
                curentBtn = dbHmlx;
                addData(1, ltHmlxs);
                btnShowOrHide(dbHmlx, dbHmd, dblhLx, dblhF);
                break;
            case R.id.db_hmd:
                popAdapter.clear();
                curentBtn = dbHmd;
                addData(2, ltHmds);
                btnShowOrHide(dbHmd, dbHmlx, dblhLx, dblhF);
                break;
            case R.id.db_lhlx:
                popAdapter.clear();
                curentBtn = dblhLx;
                addData(3, ltlhLxs);
                btnShowOrHide(dblhLx, dbHmlx, dbHmd, dblhF);
                break;
            case R.id.db_lhf:
                popAdapter.clear();
                curentBtn = dblhF;
                addData(4, ltlhFs);
                btnShowOrHide(dblhF, dbHmd, dbHmlx, dblhLx);
                break;
        }
    }

    private void addData(int selectType, String[] strings) {
        list.addAll(Arrays.asList(strings));
        popAdapter.addAll(selectType, list);
    }

    /**
     * 创建popupWindow
     * https://www.cnblogs.com/jzyhywxz/p/7039503.html
     */
    private void createPopupWindow() {
        int PopWidth = GlobalUtils.getScreenWidth(SelectKuanDaiNumActivity.this);
        int PopHeight = GlobalUtils.getScreenHeight(SelectKuanDaiNumActivity.this);
        PopWidth = (int) Math.rint(PopWidth / 2.8);
        PopHeight = (int) Math.rint(PopHeight / 3.3);
        window = new CommonPopupWindow(this, R.layout.pop_select_num_list, PopWidth, PopHeight) {
            @Override
            protected void initView() {
                View view = getContentView();
                popList = view.findViewById(R.id.pop_list);
                popAdapter = new SelectNumPopAdapter(SelectKuanDaiNumActivity.this);

                popList.setAdapter(popAdapter);

            }

            @Override
            protected void initEvent() {
                popList.setOnItemClickListener((parent, view, position, id) -> {
                    RadioButton itemView = view.findViewById(R.id.item_text);
                    itemView.setChecked(true);
                    // ListView条目点击事件发生的时候判断当前btn的选中状态,重新赋值
                    if (curentBtn != null && curentBtn.getChecked()) {
                        curentBtn.setChecked(false);
                    }

                    if (curentBtn == dbHmlx) {
                        selectPosition1 = position;
                        haomaType = hmlxs[position];
                        if (position != 0) {
                            dbHmlx.setText(ltHmlxs[position]);
                        } else {
                            dbHmlx.setText("号码类型");
                        }

                    } else if (curentBtn == dbHmd) {
                        selectPosition2 = position;
                        haomaDuan = hmds[position];
                        if (position != 0) {
                            dbHmd.setText(ltHmds[position]);
                        } else {
                            dbHmd.setText("号码段");
                        }
                    } else if (curentBtn == dblhLx) {
                        selectPosition3 = position;
                        lhLx = lhLxs[position];
                        if (position != 0) {
                            dblhLx.setText(ltlhLxs[position]);
                        } else {
                            dblhLx.setText("靓号类型");
                        }
                    } else if (curentBtn == dblhF) {
                        selectPosition4 = position;
                        lhF = lhFs[position];
                        if (position != 0) {
                            dblhF.setText(ltlhFs[position]);
                        } else {
                            dblhF.setText("靓号费");
                        }
                    }
                    popAdapter.setSelectPosition(selectPosition1, selectPosition2, selectPosition3, selectPosition4);
                    popupWindow.dismiss();
                    pullRecyclerView.autoRefresh();
                });
            }

            @Override
            protected void initWindow() {
                super.initWindow();

            }
        };
        popupWindow = window.getPopupWindow();

        // 设置显示位置属性
        layoutGravity = new LayoutGravity(LayoutGravity.CENTER_HORI | LayoutGravity.TO_BOTTOM);
    }

    /**
     * 控制btn的显示隐藏
     * btnOne
     * btnTwo
     * btnThree
     * btnFour
     */
    private void btnShowOrHide(DropdownButton btnOne, DropdownButton btnTwo,
                               DropdownButton btnThree, DropdownButton btnFour) {

        KeyBordUtils.closeInputMethod(SelectKuanDaiNumActivity.this, edSearch); // 关闭软键盘

        if (!btnOne.getChecked()) {
            // 显示
            btnOne.setChecked(true);
            if (popupWindow.isShowing()) {
                popupWindow.dismiss();
            }
            window.showBashOfAnchor(btnOne, layoutGravity, 0, 0);

            btnTwo.setChecked(false);
            btnThree.setChecked(false);
            btnFour.setChecked(false);
        } else {
            // 关闭
            btnOne.setChecked(false);
            if (popupWindow.isShowing()) {
                popupWindow.dismiss();
            }
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        if (curentBtn != null && curentBtn.getChecked()) {
            curentBtn.setChecked(false);
        }
        if (popupWindow != null && popupWindow.isShowing()) {
            popupWindow.dismiss();
        }
    }

    @Override
    protected void onDestroy() {
        if (popupWindow != null && popupWindow.isShowing()) {
            popupWindow.dismiss();
        }
        super.onDestroy();
    }
}
